import { defineComponent, ref, watch } from 'vue';
import { MciDialog, MciButton, MciTabs, MciTabPane, MciMessage, MciNotification } from '@/components/base';
import { ElMessageBox } from 'element-plus';
import { IFormItem } from './types';
import { SingleTest } from './components/SingleTest';
import { BatchTest } from './components/BatchTest';
import { getDecisionFlowFlowVars } from '@/api';

export const TestForm = defineComponent({
  props: {
    flowId: {
      type: String,
      default: ''
    }
  },
  emits: ['formSubmit', 'update:modelValue'],
  setup(props, { emit }) {
    const flowVars = ref<Record<string, any>>({});
    const formFields = ref<IFormItem[]>([]);
    const singleTestRef = ref<InstanceType<typeof SingleTest>>(null);
    const batchTestRef = ref<InstanceType<typeof BatchTest>>(null);
    const activeTab = ref('singleTest');

    const initData = async () => {
      const res = await getDecisionFlowFlowVars({ flowId: props.flowId });
      if (res) {
        formFields.value = res.map((item) => ({
          label: item.varLabel!,
          name: item.varName!,
          defaultValue: item.initValue || ''
        }));
        flowVars.value = Object.fromEntries(res.map((item) => [item.varName, item.initValue]));
      }
    };

    const onConfirm = async () => {
      if (activeTab.value === 'singleTest') {
        try {
          const singleTestResult = await singleTestRef.value?.validate();
          if (singleTestResult) {
            emit('formSubmit', singleTestResult); // 如果需要向父组件传递表单数据
            handleClose();
          } else {
            console.error('表单校验失败');
          }
        } catch (error) {
          console.error('表单校验失败', error);
        }
      } else {
        try {
          const result = await batchTestRef.value?.uploadFile();
          console.log('上传结果：', result);
          if (result && result.status === 'success') {
            ElMessageBox.alert(
              `批量测试批次号：<br />
                （请在案件中心—日志列表查看执行结果）
              `,
              '提示',
              {
                confirmButtonText: '复制批次号',
                dangerouslyUseHTMLString: true, // 添加此属性使内容按HTML解析
                callback(action: Action) {
                  if (action === 'confirm') {
                    if (navigator.clipboard) {
                      navigator.clipboard.writeText(result.data?.data).then(() => {
                        MciNotification.success('复制成功');
                        handleClose();
                      });
                    }
                  } else {
                    handleClose();
                  }
                }
              }
            );
          } else {
            MciMessage({
              message: result.message,
              type: result.status
            });
          }
        } catch (error) {
          console.error('上传过程中发生错误', error);
        }
      }
    };

    const handleClose = () => {
      emit('update:modelValue', false);
    };

    initData();

    return () => {
      return (
        <MciDialog width={540} modelValue={true} title="决策流请求参数" onClose={handleClose} customClass="max-height-dialog">
          {{
            default() {
              return (
                <MciTabs v-model={activeTab.value} type={'card'}>
                  <MciTabPane label="单笔测试" name="singleTest">
                    {activeTab.value === 'singleTest' && (
                      <SingleTest ref={singleTestRef} formFields={formFields.value} flowVars={flowVars.value} flowId={props.flowId} />
                    )}
                  </MciTabPane>
                  <MciTabPane label="批量测试" name="batchTest">
                    {activeTab.value === 'batchTest' && <BatchTest ref={batchTestRef} flowId={props.flowId} />}
                  </MciTabPane>
                </MciTabs>
              );
            },
            footer() {
              return (
                <>
                  <MciButton onClick={handleClose}>取消</MciButton>
                  <MciButton type="primary" onClick={onConfirm}>
                    确定
                  </MciButton>
                </>
              );
            }
          }}
        </MciDialog>
      );
    };
  }
});
